package com.cgt.xiaotao.order.controller;

import com.cgt.common.utils.R;
import com.cgt.xiaotao.order.service.IPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Api(tags = "阿里支付接口")
@Slf4j
@RestController
@RequestMapping("/pay")
@RequiredArgsConstructor
public class AliPayController {

    private final IPaymentService paymentService;

    @ApiOperation("阿里支付")
    @GetMapping("/ali/{orderNo}")
    public R<String> pay(@PathVariable String orderNo) {
        try {
            String res = paymentService.aliPay(orderNo);
            return R.ok(res);
        } catch (Exception e) {
            return R.fail(e.toString());
        }
    }

    // 支付宝回调接口 请求方式、接收参数和返回参数都是固定写法，不能更改
    @ApiOperation("阿里回调接口")
    @PostMapping("/callback")
    public String handleCallback(@RequestParam Map<String, String> params){
        log.info("支付宝回调:{}",params);
        // 检查支付结果是否成功
        String tradeStatus = params.get("trade_status");
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            paymentService.callback(params);
        }

        // 固定参数，必须为 success
        return "success";
    }
}
